<template>
  <div>
    <el-form ref="addFormRef" :rules="rules" :model="addForm.data" label-width="120">
      <el-row>
        <el-form-item label="车牌号码" prop="licensePlate">
          <el-input
            v-model="addForm.data.licensePlate"
            style="width: 320px"
            placeholder="请输入车牌号码"
          />
        </el-form-item>
        <el-form-item label="车主手机" prop="ownerPhone">
          <el-input
            v-model="addForm.data.ownerPhone"
            style="width: 320px"
            maxlength="11"
            placeholder="请输入车主手机"
          />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="适用范围" prop="scope">
          <el-radio-group v-model="addForm.data.scope">
            <el-radio
              v-for="item in scopeList.data"
              :key="item.id"
              :value="item.id"
              @change="scopeChange"
            >
              {{ item.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="付款方式" prop="payWay">
          <!-- <el-select
            v-model="addForm.data.payWay"
            filterable
            style="width: 320px"
            placeholder="请选择付款方式"
          >
            <el-option
              v-for="item in payWayList.data"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select> -->
          <el-radio-group v-model="addForm.data.payWay">
            <el-radio v-for="item in payWayList.data" :key="item.id" :value="item.id">
              {{ item.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="卡类型" prop="typeId">
          <el-radio-group v-model="addForm.data.typeId">
            <el-radio
              @change="getType(item)"
              v-for="item in typeList.data"
              :key="item.id"
              :value="item.id"
            >
              {{ item.name }}
              （￥{{ item.price }}/
              {{ item.type == 1 ? "月" : item.type == 2 ? "季" : "年" }}）
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="生效时间" prop="validityStart">
          <el-date-picker
            v-model="addForm.data.validityStart"
            style="width: 320px"
            type="date"
            placeholder="请选择生效时间"
            value-format="YYYY-MM-DD"
            @change="getValidityStart(addForm.data.validityStart)"
          />
        </el-form-item>
        <el-form-item label="失效时间" prop="validityEnd">
          <el-date-picker
            v-model="addForm.data.validityEnd"
            style="width: 320px"
            type="date"
            value-format="YYYY-MM-DD"
            disabled
          />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="选择数量" prop="buyUnit">
          <el-input-number
            v-model="addForm.data.buyUnit"
            style="width: 320px"
            :min="1"
            controls-position="right"
            @change="getBuyUnit(addForm.data.buyUnit)"
          />
        </el-form-item>
        <el-form-item label="购买金额" prop="buyPrice">
          <el-input v-model="addForm.data.buyPrice" style="width: 320px" disabled />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item
          label="适用场库"
          prop="lotList"
          v-if="addForm.data.scope == 3 || addForm.data.scope == 1"
        >
          <!-- <el-select
            v-model="addForm.data.lotId"
            filterable
            style="width: 320px"
            placeholder="请选择适用场库"
            @change="lotIdClick(addForm.data.lotId)"
          >
            <el-option
              v-for="item in lotIdList.data"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select> -->
          <el-cascader
            v-model="lotId"
            :options="lotIdList.data"
            style="width: 320px"
            placeholder="请选择适用场库"
            :props="{
              value: 'id',
              label: 'name',
              multiple: true,
            }"
            @change="handleLotIdChange"
            clearable
          />
        </el-form-item>
        <el-form-item
          label="适用路段"
          prop="sectionList"
          v-if="addForm.data.scope == 3 || addForm.data.scope == 2"
        >
          <!-- <el-select
            v-model="addForm.data.sectionId"
            filterable
            style="width: 320px"
            placeholder="请选择适用路段"
          >
            <el-option
              v-for="item in sectionIdList.data"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select> -->
          <el-cascader
            v-model="section"
            :options="sectionIdList.data"
            style="width: 320px"
            placeholder="请选择适用路段"
            :props="{
              value: 'id',
              label: 'name',
              multiple: true,
            }"
            @change="handleSectionChange"
            clearable
          />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="备注">
          <el-input
            v-model="addForm.data.remark"
            maxlength="20"
            show-word-limit
            type="textarea"
            style="width: 320px"
          />
        </el-form-item>
      </el-row>
      <el-form-item>
        <div class="footer">
          <div></div>
          <div>
            <el-button class="reset-btn" @click="resetForm(addFormRef)">重 置</el-button>
            <el-button class="confirm-btn" @click="submitForm(addFormRef)"
              >确 认</el-button
            >
          </div>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { getCardType, getAddCparkCard } from "../request.js";
const emits = defineEmits(["operationDone"]);

const props = defineProps({
  listData: {
    type: Object,
    default: () => {},
  },
});

console.log(props.listData);
const lotId = ref([]);
const lotIdList = reactive({
  data: [],
});
const section = ref([]);
const sectionIdList = reactive({
  data: [],
});

const scopeList = reactive({
  data: [
    {
      id: 2,
      name: "路内",
    },
    {
      id: 1,
      name: "车场",
    },
    {
      id: 3,
      name: "通用",
    },
  ],
});

const payWayList = reactive({
  data: [
    {
      id: 1,
      name: "微信",
    },
    {
      id: 2,
      name: "支付宝",
    },
    {
      id: 3,
      name: "现金",
    },
  ],
});

const typeList = reactive({
  data: [],
});

const addFormRef = ref("");
const addForm = reactive({
  data: {
    buyUnit: 1,
    validityStart: new Date().toISOString().split("T")[0],
    scope: 3,
    lotList: [],
    sectionList: [],
  },
});

const scopeChange = (value) => {
  console.log(value);
  if (value == 2) {
    addForm.data.lotList = [];
  } else if (value == 1) {
    addForm.data.sectionList = [];
  }
};

const handleLotIdChange = (value) => {
  console.log("value ===>", value);
  lotId.value = lotId.value
    .filter((item) => Array.isArray(item)) // 确保是数组
    .map((item) => item[0]);
  console.log("value ===>", lotId.value);

  addForm.data.lotList = lotIdList.data
    .filter((item) => lotId.value.includes(item.id))
    .map((item) => ({ id: item.id, name: item.name }));
};

const handleSectionChange = (value) => {
  console.log("value ===>", value);
  section.value = section.value
    .filter((item) => Array.isArray(item)) // 确保是数组
    .map((item) => item[0]);
  console.log("value ===>", section.value);

  addForm.data.sectionList = sectionIdList.data
    .filter((item) => section.value.includes(item.id))
    .map((item) => ({ id: item.id, name: item.name }));
};

const rules = reactive({
  lotList: [{ required: true, message: "请选择适用场库", trigger: "change" }],
  sectionList: [{ required: true, message: "请选择适用路段", trigger: "change" }],
  licensePlate: [{ required: true, message: "请输入车牌号码", trigger: "blur" }],
  ownerPhone: [
    { required: true, message: "请输入车主手机", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "手机号码格式不正确，请重新输入",
      trigger: "blur",
    },
  ],
  scope: [{ required: true, message: "请选择适用范围", trigger: "change" }],
  payWay: [{ required: true, message: "请选择付款方式", trigger: "change" }],
  typeId: [{ required: true, message: "请选择卡类型", trigger: "change" }],
  validityStart: [{ required: true, message: "请选择生效时间", trigger: "change" }],
  buyUnit: [{ required: true, message: "请选择选择数量", trigger: "change" }],
});

onMounted(() => {
  lotIdList.data = props.listData.lotIdList;
  sectionIdList.data = props.listData.sectionIdList;
});

// 车场名称
const lotIdClick = (val) => {
  console.log(val);
  getData();
};

// 卡类型
const getType = (val) => {
  console.log("卡类型 ===》", val);
  addForm.data.buyPrice = parseInt(addForm.data.buyUnit) * parseFloat(val.price);
  const start = new Date(addForm.data.validityStart);
  if (!addForm.data.validityStart) return;
  typeList.data.forEach((item) => {
    if (addForm.data.typeId == item.id) {
      // 卡类型 1-月卡 2-季卡 3-年卡
      let months = 0;
      switch (item.type) {
        case 1:
          months = addForm.data.buyUnit;
          break;
        case 2:
          months = addForm.data.buyUnit * 3;
          break;
        case 3:
          months = addForm.data.buyUnit * 12;
          break;
      }
      start.setMonth(start.getMonth() + months);
      const end = new Date(start);
      end.setDate(end.getDate() - 1);
      const dateString = end.toISOString().split("T")[0]; // 获取ISO日期字符串的日期部分
      // console.log(dateString);
      addForm.data.validityEnd = dateString;
    }
  });
};

// 生效时间
const getValidityStart = (val) => {
  console.log("生效时间 ===》", val);
  const start = new Date(val);
  if (!addForm.data.typeId) return;
  typeList.data.forEach((item) => {
    if (addForm.data.typeId == item.id) {
      //   console.log(item.type);
      // 卡类型 1-月卡 2-季卡 3-年卡
      let months = 0;
      switch (item.type) {
        case 1:
          months = addForm.data.buyUnit;
          break;
        case 2:
          months = addForm.data.buyUnit * 3;
          break;
        case 3:
          months = addForm.data.buyUnit * 12;
          break;
      }
      start.setMonth(start.getMonth() + months);
      const end = new Date(start);
      end.setDate(end.getDate() - 1);
      const dateString = end.toISOString().split("T")[0]; // 获取ISO日期字符串的日期部分
      // console.log(dateString);
      addForm.data.validityEnd = dateString;
    }
  });
};

// 选择数量
const getBuyUnit = (val) => {
  console.log("数量 ===》", val);
  if (!addForm.data.typeId) return;
  const start = new Date(addForm.data.validityStart);
  typeList.data.forEach((item) => {
    if (addForm.data.typeId == item.id) {
      console.log(item.price);
      addForm.data.buyPrice = parseInt(val) * parseFloat(item.price);
      // 卡类型 1-月卡 2-季卡 3-年卡
      if (!addForm.data.validityStart) return;
      let months = 0;
      switch (item.type) {
        case 1:
          months = addForm.data.buyUnit;
          break;
        case 2:
          months = addForm.data.buyUnit * 3;
          break;
        case 3:
          months = addForm.data.buyUnit * 12;
          break;
      }
      start.setMonth(start.getMonth() + months);
      const end = new Date(start);
      end.setDate(end.getDate() - 1);
      const dateString = end.toISOString().split("T")[0]; // 获取ISO日期字符串的日期部分
      // console.log(dateString);
      addForm.data.validityEnd = dateString;
    }
  });
};

const getData = async () => {
  await getCardType({
    lotId: addForm.data.lotId,
  }).then((res) => {
    console.log(res);
    typeList.data = res.data.result;
    addForm.data.typeId = typeList.data[0].id;

    const start = new Date(addForm.data.validityStart);
    typeList.data.forEach((item) => {
      if (addForm.data.typeId == item.id) {
      console.log(item);
      addForm.data.buyPrice = parseInt(addForm.data.buyUnit) * parseFloat(item.price);
      
      // 卡类型 1-月卡 2-季卡 3-年卡
      let months = 0;
      switch (item.type) {
        case 1:
          months = addForm.data.buyUnit;
          break;
        case 2:
          months = addForm.data.buyUnit * 3;
          break;
        case 3:
          months = addForm.data.buyUnit * 12;
          break;
      }
      start.setMonth(start.getMonth() + months);
      const end = new Date(start);
      end.setDate(end.getDate() - 1);
      const dateString = end.toISOString().split("T")[0]; // 获取ISO日期字符串的日期部分
      // console.log(dateString);
        addForm.data.validityEnd = dateString;
    }
  });
  });
};

getData();

const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      lotIdList.data.forEach((item) => {
        if (addForm.data.lotId == item.id) {
          addForm.data.lotName = item.name;
        }
      });
      getAddCparkCard(addForm.data).then((res) => {
        if (res.data.code === 0) {
          ElMessage({
            type: "success",
            message: res.data.result,
          });
          emits("operationDone");
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    }
  });
};

const resetForm = async (formEl) => {
  if (!formEl) return;
  addForm.data = {
    buyUnit: 1,
  };
  getData();
  formEl.resetFields();
};
</script>

<style lang="less" scoped>
.footer {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.reset-btn {
  width: 65px;
  height: 32px;
  background: #ffffff;
  border-radius: 2px;
  border: 1px solid #d9d9d9;
  font-weight: 400;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.65);
}
.confirm-btn {
  width: 65px;
  height: 32px;
  background: #007aff;
  border-radius: 2px;
  font-weight: 400;
  font-size: 14px;
  color: #ffffff;
}
</style>
